package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.pojo.Role;
import com.itheima.pojo.RoleVO;
import com.itheima.service.RoleService;
import com.itheima.dao.RoleMapper;
import com.itheima.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;


@Service
public class RoleServiceImpl implements RoleService {


    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private IdWorker idWorker;    //1.新增角色信息
    @Override
    public void add(RoleVO roleVO) {
        Role role = new Role();
        role.setCategoryMenuUids(roleVO.getCategoryMenuUids());
        role.setRoleName(roleVO.getRoleName());
        role.setStatus(1);
        role.setSummary(roleVO.getSummary());
        role.setUid(idWorker.nextId()+"");
        roleMapper.insert(role);
    }

    //2.删除角色信息
    @Override
    public void delete(RoleVO roleVO) {
        String uid = roleVO.getUid();
        roleMapper.deleteByPrimaryKey(uid);
    }

    //3.更新角色信息
    @Override
    public void edit(RoleVO roleVO) {

        Role role = new Role();
        role.setCategoryMenuUids(roleVO.getCategoryMenuUids());
        role.setRoleName(roleVO.getRoleName());
        role.setStatus(roleVO.getStatus());
        role.setSummary(roleVO.getSummary());
        role.setUid(roleVO.getUid());
        roleMapper.updateByPrimaryKey(role);
    }

    //4.获取角色信息列表
    @Override
    public Page<Role> getList(RoleVO roleVO) {

        PageHelper.startPage(roleVO.getCurrentPage(),roleVO.getPageSize());
        Example example = createExample(roleVO);
        return (Page<Role>)roleMapper.selectByExample(example);
    }

    /*
     * 封装查询条件对象*/
    private Example createExample(RoleVO roleVO) {
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        if ( roleVO!= null) {
            // 根据标签名称模糊查询
            if( roleVO.getKeyword()!=null && !"".equals( roleVO.getKeyword())){
                criteria.andLike("roleName","%"+ roleVO.getKeyword()+"%");
            }
        }
        return example;
    }

}
